import Request from '@/js_sdk/luch-request/luch-request/index.js'
import errorCode from '@/utils/errorCode'
import {
	getToken
} from '@/utils/auth'

import config from '@/utils/config.js'
let BASE_API = config.BASE_API



// import qs from 'qs'
const http = new Request({
	baseURL: BASE_API, //设置请求的base url
	timeout: 300000, //超时时长5分钟,
	header: {
		'Content-Type': 'application/json;charset=UTF-8;'
		// 'Content-Type': 'multipart/form-data;application/json;charset=UTF-8;'
	}
})

//请求拦截器
http.interceptors.request.use((config) => { // 可使用async await 做异步操作


	uni.showLoading({
		title: "加载中..."
	})
	const token = getToken();
	if (token) {
		config.header = {
			"Authorization": 'Bearer ' + token
		}
	}

	if (config.method === 'POST') {
		config.data = JSON.stringify(config.data);
	}
	return config
}, error => {
	return Promise.resolve(error)
})

// 响应拦截器
http.interceptors.response.use((res) => {
	uni.hideLoading()

	// 未设置状态码则默认成功状态
	const code = res.data.code || 200;


	// 获取错误信息
	const msg = errorCode[code] || res.data.msg || errorCode['default']
	if (code === 401) {
		uni.showModal({
			title: "系统提示",
			content: "登录状态已过期，您可以继续留在该页面，或者重新登录",
			showCancel: true,
			success: () => {
				// 确定跳转到登录页面
				uni.navigateTo({
					url: "/pages/normal/login/login"
				})
			},
			fail: () => {
				// 留在本页面不处理
			}
		})
	} else if (code === 500) {
		return Promise.reject(new Error(msg))
	} else if (code !== 200) {
		return Promise.reject('error')
	} else {
		return res.data
	}

}, (error) => {
	let {
		message
	} = error;

	if (message == "Network Error") {
		message = "后端接口连接异常";
	} else if (message.includes("timeout")) {
		message = "系统接口请求超时";
	} else if (message.includes("Request failed with status code")) {
		message = "系统接口" + message.substr(message.length - 3) + "异常";
	}
	uni.showToast({
		title: message || "系统问题,请联系管理员！",
		icon: "none",
		duration: 500,
		success: () => {
			return data
		}
	})

	return Promise.reject(error)
})

export default http;
